package com.lori.netshop.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.lori.netshop.pojo.TbUser;
import com.lori.netshop.service.UserService;
import com.lori.netshop.util.CookieUtils;
import com.lori.netshop.util.NetshopResult;
import com.lori.netshop.util.StringUtil;
/**
 * 拦截登录
 * @author Administrator
 *
 */
public class LoginInterceptor extends HandlerInterceptorAdapter{
	@Autowired
	private UserService userServiceimp;
	@Value("${BASE_SSO}")
	private String BASE_SSO;
	@Value("${SSO_LOGIN}")
	private String SSO_LOGIN;
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
		throws Exception {
		//从cookie中获得token
		String cookieValue = CookieUtils.getCookieValue(request, "token");
		//获得登录状态
		if(!StringUtil.isEmpty(cookieValue)){
			NetshopResult result = userServiceimp.findByToken(cookieValue);
			if(result.getStatus() == 200){
				//获取用户对象
				TbUser user = (TbUser) result.getData();
				//存入request
				request.setAttribute("user", user);
				return true;
			}else{
				//没有的话带着url跳到登录页面
				response.sendRedirect(BASE_SSO+SSO_LOGIN+"?redirectUrl="+request.getRequestURL());
				return false;
			}
		}else{
			//没有的话带着url跳到登录页面
			response.sendRedirect(BASE_SSO+SSO_LOGIN+"?redirectUrl="+request.getRequestURL());
			return false;
		}
	}
}
